(function() {

    var socket;
    var currentUserData;

    $(document).on('socketActivated', function(event) {

        socket = event.socket;
        currentUserData = event.currentUserData;

        if (socket) {
            socket.on('document_created', function(data) {
                var documentFormId = data.documentFormId;
                var iframe = $('.fl-report-wrapper-content[fl-data-form-id=' + documentFormId + '] > div > iframe');

                //  refresh the iframe
                iframe[0].contentWindow.location.reload(true);
            });     
        }   

    });

    /**
     * Event triggered by submitting a new document to formalistics.
     * This will then send an event to the socket server saying that a new
     * document is created.
     */
    $(document).on('documentCreated', function(event) {
        //  validate if the event object is missing or is not supplied
        if (typeof event === 'undefined') {
            return;
        }

        var documentFormId = event.documentData.formId;

        if (socket) {
            socket.emit('publish_to_address', {
                publishAddresses: ['live_reports_' + documentFormId],
                event: 'document_created',
                data: {
                    documentFormId: documentFormId
                }
            });
        }
        

    });

})();